package com.levy.effect.ioc.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.levy.effect.ioc.annotation.IocBean;

/**
 * 扫描器
 * 
 * @author levy
 *
 */
public class Scaner {

	/***
	 * 1.首先扫描指定的包，获取iocbean并实例化
	 * 
	 * 
	 * @return
	 */
	public static void registerBeans(ConcurrentHashMap<Class<?>, Object> type2beans,
			ConcurrentHashMap<String, Object> name2beans, String... basepaths) {
		for (String basepath : basepaths) {
			String path = basepath.replace(".", "/");
			try {
				Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(path);
				while (resources.hasMoreElements()) {
					URL url = resources.nextElement();
					String protocol = url.getProtocol();
					if ("file".equals(protocol)) {// 处理文件
						System.out.println("扫描文件路径" + url.toString());
						findClass(path, url.getFile(), type2beans, name2beans);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void findClass(String packpath, String filePath, Map<Class<?>, Object> type2beans,
			Map<String, Object> name2beans) {
		File backpath = new File(filePath);
		File[] listFiles = backpath.listFiles(new FileFilter() {
			public boolean accept(File file) {
				return file.isDirectory() || file.getName().endsWith(".class");
			}
		});
		for (File file : listFiles) {
			if (file.isDirectory()) {
				findClass(packpath + "." + file.getName(), file.getPath(), type2beans, name2beans);
			}

			else {
				try {
					String className = file.getName().substring(0, file.getName().length() - 6);
					Class<?> clazz = Thread.currentThread().getContextClassLoader()
							.loadClass(packpath.replace("/", ".") + "." + className);
					IocBean iocBeanAnno = clazz.getAnnotation(IocBean.class);
					if (iocBeanAnno == null)
						continue;
					try {
						Object instance = clazz.newInstance();
						type2beans.put(clazz, instance);
						String beanV = iocBeanAnno.value();
						if (beanV == null || "".equals(beanV))
							name2beans.put(firstLowerCase(className), instance);
						else
							name2beans.put(beanV, instance);
					} catch (Exception e) {
						throw new RuntimeException("加载类失败:" + className);
					}
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static String firstLowerCase(String str) {
		char[] temp = new char[1];
		temp[0] = str.charAt(0);
		String temps = new String(temp);
		String result = "";
		if (temp[0] >= 'A' && temp[0] <= 'Z') {
			result = str.replaceFirst(temps, temps.toLowerCase());
		}
		return result;
	}

	public static void main(String[] args) {
		String firstLowerCase = new Scaner().firstLowerCase("ILOVEYOU");
		System.out.println(firstLowerCase);
	}

}
